<template>
    <a-upload
        ref="uploadRef"
        v-model:fileList="currentFileList"
        :limit="limit"
        :multiple="multiple"
        :disabled="disabled"
        :show-file-list="showFileList"
        @before-upload="beforeUpload"
        :custom-request="customRequest"
        :accept="accept"
        :maxCount="maxCount"
        list-type="picture-card"
    >
        <div v-if="fileList.length < 8">
            <plus-outlined />
            <div style="margin-top: 8px">{{ uploadText }}</div>
        </div>
    </a-upload>
</template>

<script lang="ts">
    export default {
        name: 'CustomUpload',
    };
</script>

<script lang="ts" setup>
    import { PropType, ref, computed } from 'vue';
    import { message } from 'ant-design-vue';
    import { PlusOutlined } from '@ant-design/icons-vue';
    import { isEmpty, isNumber } from 'lodash-es';
    import { uploadFile } from '@/api/common';

    const uploadRef = ref<any>(null);
    const props = defineProps({
        uploadText: {
            type: String as PropType<string>,
            default() {
                return '上传';
            },
        },
        limitSize: {
            type: Number as PropType<number>,
            default() {
                return 500;
            },
        },
        limit: {
            type: Number as PropType<number>,
            default() {
                return 0;
            },
        },
        maxCount: {
            type: Number as PropType<number>,
            default() {
                return 9;
            },
        },
        multiple: {
            type: Boolean as PropType<boolean>,
            default() {
                return false;
            },
        },
        fileList: {
            type: Array as PropType<FileItem[]>,
            default() {
                return [];
            },
        },
        disabled: {
            type: Boolean as PropType<boolean>,
            default() {
                return false;
            },
        },
        showFileList: {
            type: Boolean as PropType<boolean>,
            default() {
                return true;
            },
        },
        accept: {
            type: String as PropType<string>,
            default() {
                return '';
            },
        },
    });
    const emits = defineEmits(['update:fileList']);

    const beforeUpload = (file: File): any => {
        console.log(file);

        return new Promise((resolve, reject) => {
            if (file.size === 0) {
                message.warning(`文件大小不能为0`);
                reject(new Error(`文件大小不能为0`));
            }
            if (isNumber(props.limitSize)) {
                if (file.size / 1024 / 1024 > props.limitSize) {
                    message.warning(`文件大小应该小于${props.limitSize}M`);
                    reject(new Error(`文件大小应该小于${props.limitSize}M`));
                }
                resolve(true);
            } else {
                resolve(true);
            }
        });
    };

    const currentFileList = computed({
        get: () => {
            return props.fileList.map((item: any) => {
                console.log(item, 'get');

                return {
                    ...item,
                };
            });
        },
        set: val => {
            console.log(val, 'set');

            emits(
                'update:fileList',
                val.map((item: any) => {
                    const { response, status, name, uid } = item;
                    if (!isEmpty(response) && status === 'done') {
                        const { data } = response;
                        console.log(data, response);
                        data.url = data.viewAddress;
                        return {
                            url: data.viewAddress,
                            ...data,
                            name,
                            status: 'done',
                            uid,
                        };
                    }
                    return item;
                }),
            );
        },
    });

    const customRequest = (options: any) => {
        console.log(options);

        const fd = new FormData();
        fd.append('file', options.file);

        uploadFile(fd, {
            onUploadProgress: ev => {
                // ev - axios 上传进度实例，上传过程触发多次
                // ev.loaded 当前已上传内容的大小，ev.total - 本次上传请求内容总大小
                console.log(ev);
                const percent = (ev.loaded / ev.total) * 100;
                // 计算出上传进度，调用组件进度条方法
                options.onProgress({ percent });
            },
        })
            .then(res => {
                console.log(res);
                if (!isEmpty(res.data)) {
                    options.onSuccess(res, options);
                }
            })
            .catch(err => {
                // 调用实例的失败方法通知组件该文件上传失败
                options.onError(err);
            });
    };
</script>

<style lang="less" scoped></style>
